package com.fubowen.lepton.engine.impl

import com.fubowen.lepton.engine.ISearchEngine
import com.fubowen.lepton.ui.search.recycler.Search
import kotlinx.coroutines.flow.flow
import org.jsoup.Jsoup

class BingSearchEngine : ISearchEngine {

    private var _first: Int = 0
    private var _keyword: String = ""
    private var _currentIndex = 0

    override val isEnable: Boolean = false

    override fun getUrl(keyword: String?): String? {
        if (keyword.isNullOrBlank()) {
            return null
        }
        if (keyword != _keyword) {
            _first = 0
        }
        _keyword = keyword
        return "https://cn.bing.com/search?q=$_keyword&first=$_first"
    }

    override fun getSearchResultFlow(keyword: String?) = flow {
        val url = getUrl(keyword)
        if (!url.isNullOrEmpty()) {
            val document = Jsoup.connect(url).userAgent("Android").get()
            val list = document.getElementsByClass("b_algo")
            list.forEach {
                val title = it.getElementsByTag("H2")
                val content = it.getElementsByClass("b_algoSlug")
                val search = Search()
                search.id = _currentIndex
                search.title = title?.text()
                search.description = content?.text()
                search.titleHtml = title.outerHtml()
                search.descriptionHtml = content?.outerHtml()
                val urlElement = it.getElementsByClass("tilk").firstOrNull()
                search.url = urlElement?.attr("href")
                _currentIndex++
                emit(search)
            }
        }
    }
}